<template>
	<el-cascader
		class="cl-cascader"
		ref="cascader"
		:value="value"
		v-bind="$props"
		v-on="$listeners"
		@visible-change="visibleChange"
		@change="change"
	>
		<slot slot="empty" name="empty" />
		<template slot-scope="scope">
			<slot v-bind="scope" />
		</template>
	</el-cascader>
</template>
<script>
import { addClass, removeClass } from "@/utils";
import { Cascader } from "element-ui";
export default {
	name: "cl-cascader",
	props: {
		...Cascader.props,
		filterPlaceholder: {
			type: String,
			default: "请输入关键字搜索"
		}
	},
	data() {
		return {
			visible: false,
			height: 26
		};
	},
	mounted() {
		let cascader = this.$refs?.cascader?.$el;
		this.height = cascader.clientHeight;
	},
	methods: {
		visibleChange(v) {
			this.visible = v;
			this.$emit("visible-change", v);
			if (!this.props?.multiple || !this.filterable) return;
			let cascader = this.$refs?.cascader?.$el;
			let tags = cascader?.querySelector?.(".el-cascader__tags");
			let input = cascader?.querySelector?.(".el-cascader__search-input");
			if (!input) return;
			input.value = "";
			tags.style.height = this.height - 5 + "px";
			input.setAttribute?.("placeholder", this.filterPlaceholder);
			if (v) {
				input.focus();
				addClass(input, "is-focus");
				return;
			}
			removeClass(input, "is-focus");
		},
		change(v) {
			// this.$emit("change", v);
			if (!this.props?.multiple || !this.filterable) return;
			setTimeout(() => {
				this.$nextTick(() => {
					let cascader = this.$refs?.cascader?.$el;
					// cascader.style.height = this.height - 2 + "px";
					let input = cascader?.querySelector?.(".el-cascader__search-input");
					let tags = cascader?.querySelectorAll?.(".el-cascader__tags .el-tag");
					if (tags.length > 0) {
						if (tags.length == 2) {
							tags[0].style.maxWidth = `calc(100% - ${tags[1].clientWidth + 15}px)`;
						} else {
							tags[0].style.maxWidth = "100%";
						}
					}

					if (!input) return;
					input.value = "";
					// input?.focus();
					input?.setAttribute?.("placeholder", this.filterPlaceholder);
				});
			}, 50);
		}
	}
};
</script>
<style lang="scss" scoped>
.cl-cascader {
	::v-deep {
		.el-cascader__search-input {
			opacity: 0;
			transition: opacity 0.15s linear;
			position: absolute;
			top: 0;
			left: 0;
			width: 100% !important;
			height: calc(100% - 1px);
			background: #fff;
			margin: 0;
			margin-left: 6px;
			padding-left: 10px;
			z-index: -1;
			&::placeholder {
				color: #c0c4cc;
				font-size: 12px;
			}
			&.is-focus {
				opacity: 1;
				z-index: 1;
			}
		}
	}
}
</style>
